package org.example.java_chatroom.api;

import org.example.java_chatroom.component.OnlineUserManager;
import org.example.java_chatroom.model.AddFriendRequest;
import org.example.java_chatroom.model.Friend;
import org.example.java_chatroom.model.FriendMapper;
import org.example.java_chatroom.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author @fiber-cloud
 * @Date 2025/11/4 14:31
 * 好友管理相关操作
 */

@RestController
public class FriendAPI {
    @Resource
    private FriendMapper friendMapper;



    //查询当前用户的好友列表
    @GetMapping("/friendList")
    @ResponseBody
    public Object getFriendList(HttpServletRequest req){
        // 1.从会话中，获取到userId是谁
        HttpSession session = req.getSession(false);
        if (session == null){
            //会话并不存在,未登录
            System.out.println("[getFriendList] session 不存在");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            //user为空，说明用户不存在
            System.out.println("[getFriendList] user 不存在");
            return new ArrayList<Friend>();
        }

        // 2.根据userId，从数据库查询数据
        List<Friend> friend = friendMapper.selectFriendList(user.getUserId());

        return friend;
    }

    /**
     * 搜索好友接口
     * GET /FindFriends?keyword=搜索词
     */
// 修改 FriendAPI 中的 findFriends 方法
    @GetMapping("/findFriends")
    public Map<String, Object> findFriends(@RequestParam String keyword,
                                           HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 调试：打印所有 Session 属性
            System.out.println("=== FindFriends Session 调试 ===");
            System.out.println("Session ID: " + session.getId());
            System.out.println("Session 所有属性:");
            java.util.Enumeration<String> attributeNames = session.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String name = attributeNames.nextElement();
                System.out.println("  " + name + ": " + session.getAttribute(name));
            }

            // 从 Session 中获取 User 对象
            Object userObj = session.getAttribute("user");

            if (userObj == null) {
                System.out.println("Session 中未找到 user 对象，用户未登录");
                response.put("success", false);
                response.put("message", "用户未登录");
                response.put("data", null);
                return response;
            }

            // 处理 User 对象
            Integer userId = null;
            String username = null;

            if (userObj instanceof org.example.java_chatroom.model.User) {
                // 如果是 User 对象
                org.example.java_chatroom.model.User user = (org.example.java_chatroom.model.User) userObj;
                userId = user.getUserId();
                username = user.getUsername();
                System.out.println("从 User 对象获取用户ID: " + userId + ", 用户名: " + username);
            } else {
                // 如果是 Map 或其他类型（备用方案）
                System.out.println("user 对象类型: " + userObj.getClass().getName());

                // 尝试从 Map 中获取
                if (userObj instanceof java.util.Map) {
                    java.util.Map<?, ?> userMap = (java.util.Map<?, ?>) userObj;
                    Object idObj = userMap.get("userId");
                    if (idObj != null) {
                        userId = Integer.parseInt(idObj.toString());
                        System.out.println("从 user Map 获取用户ID: " + userId);
                    }
                }
            }

            if (userId == null) {
                System.out.println("无法从 user 对象中提取用户ID");
                response.put("success", false);
                response.put("message", "用户信息不完整");
                response.put("data", null);
                return response;
            }

            System.out.println("用户ID: " + userId + ", 搜索关键词: " + keyword);

            // 参数验证
            if (keyword == null || keyword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "搜索关键词不能为空");
                response.put("data", null);
                return response;
            }

            String searchKeyword = keyword.trim();
            if (searchKeyword.length() > 50) {
                searchKeyword = searchKeyword.substring(0, 50);
            }

            // 执行搜索
            List<Friend> friends = friendMapper.findFriendsByKeyword(userId, searchKeyword);

            response.put("success", true);
            response.put("message", "搜索成功");
            response.put("data", friends);

            System.out.println("搜索完成，找到 " + friends.size() + " 个结果");

        } catch (Exception e) {
            System.err.println("搜索好友时发生错误: " + e.getMessage());
            e.printStackTrace();

            response.put("success", false);
            response.put("message", "搜索失败: " + e.getMessage());
            response.put("data", null);
        }

        return response;
    }



    // 搜索用户 API - 对应前端 GET /findAllFriends?name=zhangsan
    @GetMapping("/findAllFriends")
    public Map<String, Object> findAllFriends(@RequestParam String name, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户是否登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            // 搜索用户 - 使用新方法 searchUsersByName
            List<User> users = friendMapper.searchUsersByName(name, currentUser.getUserId());

            response.put("success", true);
            response.put("data", users);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "搜索用户失败");
            return response;
        }
    }

    // 发送添加好友请求 API - 对应前端 GET /addFriend?name=zhangsan&reason=xxx
    @GetMapping("/addFriend")
    public Map<String, Object> addFriend(@RequestParam String name,
                                         @RequestParam(required = false) String reason,
                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户是否登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            // 查找目标用户
            User targetUser = friendMapper.findUserByName(name);
            if (targetUser == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return response;
            }

            // 不能添加自己为好友
            if (targetUser.getUserId() == currentUser.getUserId()) {
                response.put("success", false);
                response.put("message", "不能添加自己为好友");
                return response;
            }

            // 检查是否已经是好友
            int friendExists = friendMapper.checkFriendExists(currentUser.getUserId(), targetUser.getUserId());
            if (friendExists > 0) {
                response.put("success", false);
                response.put("message", "已经是好友关系");
                return response;
            }

            // 检查是否已经发送过好友请求
            int requestExists = friendMapper.checkRequestExists(currentUser.getUserId(), targetUser.getUserId());
            if (requestExists > 0) {
                response.put("success", false);
                response.put("message", "已经发送过好友请求，请等待对方处理");
                return response;
            }

            // 添加好友请求
            int result = friendMapper.addFriendRequest(currentUser.getUserId(), targetUser.getUserId(), reason);

            if (result > 0) {
                response.put("success", true);
                response.put("message", "好友请求发送成功");
            } else {
                response.put("success", false);
                response.put("message", "发送好友请求失败");
            }

            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "发送好友请求失败");
            return response;
        }
    }

    // 获取好友请求 API - 对应前端 GET /getFriendRequest
    // 获取好友请求 API
    @GetMapping("/getFriendRequest")
    public Map<String, Object> getFriendRequest(HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户是否登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            System.out.println("用户未登录，无法获取好友请求");
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        System.out.println("获取用户 " + currentUser.getUserId() + " 的好友请求");

        try {
            // 获取好友请求列表
            List<AddFriendRequest> requests = friendMapper.getFriendRequests(currentUser.getUserId());

            System.out.println("查询到的请求数量: " + (requests != null ? requests.size() : "null"));
            if (requests != null) {
                for (AddFriendRequest req : requests) {
                    System.out.println("请求详情: " +
                            "ID=" + req.getRequestId() +
                            ", 来自=" + req.getFromUserName() +
                            ", 理由=" + req.getReason());
                }
            }

            response.put("success", true);
            response.put("data", requests);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取好友请求失败");
            return response;
        }
    }

    // 接受好友请求 API - 对应前端 GET /acceptFriend?friendId=1
    @GetMapping("/acceptFriend")
    public Map<String, Object> acceptFriend(@RequestParam int friendId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户是否登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            // 获取好友请求
            AddFriendRequest request = friendMapper.getFriendRequestById(friendId);
            if (request == null) {
                response.put("success", false);
                response.put("message", "好友请求不存在");
                return response;
            }

            // 验证当前用户是否有权限处理这个请求
            if (request.getToUserId() != currentUser.getUserId()) {
                response.put("success", false);
                response.put("message", "无权处理此请求");
                return response;
            }

            // 更新请求状态为已接受
            int updateResult = friendMapper.acceptFriendRequest(friendId);
            if (updateResult == 0) {
                response.put("success", false);
                response.put("message", "更新请求状态失败");
                return response;
            }

            // 建立双向好友关系
            friendMapper.addFriend(request.getFromUserId(), request.getToUserId()); // A -> B
            friendMapper.addFriend(request.getToUserId(), request.getFromUserId()); // B -> A

            response.put("success", true);
            response.put("message", "好友添加成功");
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "接受好友请求失败");
            return response;
        }
    }

    // 拒绝好友请求 API - 对应前端 GET /rejectFriend?friendId=1
    @GetMapping("/rejectFriend")
    public Map<String, Object> rejectFriend(@RequestParam int friendId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户是否登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            // 获取好友请求
            AddFriendRequest request = friendMapper.getFriendRequestById(friendId);
            if (request == null) {
                response.put("success", false);
                response.put("message", "好友请求不存在");
                return response;
            }

            // 验证当前用户是否有权限处理这个请求
            if (request.getToUserId() != currentUser.getUserId()) {
                response.put("success", false);
                response.put("message", "无权处理此请求");
                return response;
            }

            // 更新请求状态为已拒绝
            int result = friendMapper.rejectFriendRequest(friendId);

            if (result > 0) {
                response.put("success", true);
                response.put("message", "已拒绝好友请求");
            } else {
                response.put("success", false);
                response.put("message", "拒绝好友请求失败");
            }

            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "拒绝好友请求失败");
            return response;
        }
    }

}
